﻿#include "CTotrisGame.h"
#include "MiscDefine.h"
#include <stdlib.h>
#include <string.h>

int construct_toris_game(CTotrisGame* thes) {
	return 0;
}

int is_overlap_spare_part(const CSparePart* p1, const CSparePart* p2) {
    int i = 0;
    int j = 0;
    if(0 == p1 || 0 == p2) return TOS_OVERLAP_ERROR;
    for(i = 0; i < p1->atom_cnt; ++i) {
        for(j = 0; j < p2->atom_cnt; ++j) {
            if((p1->origin.x + p1->atoms[i].coord.x == p2->origin.x + p2->atoms[j].coord.x) &&
                (p1->origin.y + p1->atoms[i].coord.y == p2->origin.y + p2->atoms[j].coord.y)) {
                return TOS_OVERLAP;
            }
        }
    }
    return TOS_NOT_OVERLAP;
}

int is_overlap_piles(const CSparePart* p1, const char* piles) {
    int i = 0;
    if(0 == p1 || 0 == piles) return TOS_OVERLAP_ERROR;
    for(i = 0; i < p1->atom_cnt; ++i) {
        int x = p1->origin.x + p1->atoms[i].coord.x;
        int y = p1->origin.y + p1->atoms[i].coord.y;
        if(piles[y * ITEM_WIDTH_COUNT + x]) { //------>
            return TOS_OVERLAP;
        }
    }
    return TOS_NOT_OVERLAP;
}

int is_need_pile(const CSparePart* p, const char* piles) {
	int i = 0;
	if (TOS_OVERLAP == is_overlap_piles(p, piles)) {
		//SERVER_DEBUG("need pile. [%d, %d]", p->origin.x, p->origin.y);
		return TOS_YES;
	}

	for (i = 0; i < p->atom_cnt; ++i) {
		if (p->origin.y + p->atoms[i].coord.y >= ITEM_HEIGHT_COUNT) {
			//SERVER_DEBUG("need pile. [%d, %d]", p->origin.x, p->origin.y);
			return TOS_YES;
		}
	}
	return TOS_NO;
}

int do_pile(const CSparePart* p, char* piles) {
	int i = 0;
	for (i = 0; i < p->atom_cnt; ++i) {
		int x = p->origin.x + p->atoms[i].coord.x;
		int y = p->origin.y + p->atoms[i].coord.y;
		piles[y * ITEM_WIDTH_COUNT + x] = p->atoms[i].data; //-------->scan
	}
	return 0;
}

int is_have_full_row(const char* piles, char which_row[ITEM_HEIGHT_COUNT], int* count) {
	int x = 0;
	int y = 0;
	char* which = 0;
	*count = 0;
	for (y = 0; y < ITEM_HEIGHT_COUNT; ++y) {
		for (x = 0; x < ITEM_WIDTH_COUNT; ++x) {
			if (!piles[y * ITEM_WIDTH_COUNT + x]) {
				break;
			}
		}
		if (x != ITEM_WIDTH_COUNT) {
			continue;
		}
		which_row[*count] = y;
		*count += 1;
	}
	if (*count == 0) {
		return TOS_NO;
	}
	return TOS_YES;
}

int do_erase_full_row(char* piles, char row_num) {
	int x = 0;
	int y = 0;
	for (y = row_num; y > 0; --y) {
		memcpy(&piles[y * ITEM_WIDTH_COUNT], &piles[(y - 1) * ITEM_WIDTH_COUNT], sizeof(piles[0]) * ITEM_WIDTH_COUNT);
	}
	return 0;
}